import sys
import os
import subprocess
from pathlib import Path

def install_requirements(pip_path):
    """安装项目依赖"""
    try:
        print("\033[93m正在安装项目依赖...\033[0m")
        subprocess.run([str(pip_path), "install", "-r", "requirements.txt"], check=True)
        print("\033[92m√ 依赖安装成功!\033[0m")
        return True
    except subprocess.CalledProcessError as e:
        print(f"\033[91m依赖安装失败: {e}\033[0m")
        return False

def activate_venv():
    """激活虚拟环境"""
    venv_path = Path("venv")
    if os.name == "nt":  # Windows
        python_path = venv_path / "Scripts" / "python.exe"
        pip_path = venv_path / "Scripts" / "pip.exe"
    else:  # Linux/Mac
        python_path = venv_path / "bin" / "python"
        pip_path = venv_path / "bin" / "pip"
    
    if not python_path.exists():
        return None, None
    
    return python_path, pip_path

def check_and_create_venv():
    """检查是否在虚拟环境中运行,如果不在则创建并激活"""
    venv_path = Path("venv")
    
    # 检查是否在虚拟环境中
    in_venv = sys.prefix != sys.base_prefix
    
    if in_venv:
        print("\033[92m√ 已在虚拟环境中运行\033[0m")
        return True, None
    
    # 尝试激活已存在的虚拟环境
    python_path, pip_path = activate_venv()
    if python_path is not None:
        print("\033[92m√ 已找到现有虚拟环境\033[0m")
        # 检查并安装依赖
        if not install_requirements(pip_path):
            return False, None
        return True, python_path
    
    print("\033[93m未检测到虚拟环境,正在创建...\033[0m")
    
    try:
        # 创建虚拟环境
        subprocess.run([sys.executable, "-m", "venv", "venv"], check=True)
        print("\033[92m√ 虚拟环境创建成功!\033[0m")
        
        # 获取新创建的虚拟环境路径
        python_path, pip_path = activate_venv()
        if python_path is None:
            print("\033[91m虚拟环境激活失败\033[0m")
            return False, None
        
        # 安装依赖
        if not install_requirements(pip_path):
            return False, None
        
        print("\033[92m√ 环境配置完成!\033[0m")
        return True, python_path
            
    except subprocess.CalledProcessError as e:
        print(f"\033[91m创建虚拟环境失败: {e}\033[0m")
        return False, None

def main():
    # 检查并创建虚拟环境
    success, python_path = check_and_create_venv()
    if not success:
        sys.exit(1)
    
    if python_path and not sys.prefix != sys.base_prefix:
        # 如果不在虚拟环境中，则使用虚拟环境的Python重新运行此脚本
        try:
            os.execv(str(python_path), [str(python_path), __file__])
        except OSError as e:
            print(f"\033[91m切换到虚拟环境失败: {e}\033[0m")
            sys.exit(1)
    
    # 现在环境已准备好，可以安全地导入依赖包
    try:
        import uvicorn
        from migrations import migrate
        
        # 执行数据库迁移
        migrate()
        
        # 启动服务器
        uvicorn.run(
            "app.main:app",
            host="127.0.0.1",
            port=8000,
            reload=True,
            reload_dirs=[str(Path(__file__).parent)]
        )
    except ImportError as e:
        print(f"\033[91m导入依赖包失败: {e}\033[0m")
        print("请确保所有依赖都已正确安装")
        sys.exit(1)

if __name__ == "__main__":
    main()